<?php
require_once 'conf.php';

/**
 * class Connection
 *
 * Description for class Connection
 *
 * @author: hqlam
*/
class Connection  {

	private $con;
	
	private function __construct() {
		$this->con = mysql_connect($GLOBALS['host'], $GLOBALS['username'], $GLOBALS['password']);

		if (!$this->con) {
			throw new Exception('Could not connect to database.');
		}
		
		if (!mysql_select_db($GLOBALS['database'], $this->con)) {
			throw new Exception('Database not exist.');
		}
		mysql_query("set names 'utf8'", $this->con);
	}
	
	private static $instance = null;	// Connection
	
	/**
	 * getInstance
	 *
	 * @return php connection 
	 * Singleton Pattern
	 */
	public static function getInstance() {
		if (Connection::$instance == null)
			Connection::$instance = new Connection();
		return Connection::$instance;
	}

	/**
	 * Execute Query
	 *
	 * @return query iterator 
	 */
	public function executeQuery($query) {
		$result = array();
		$lst = mysql_query($query, $this->con);
		
		return new QueryIterator($lst);
	}

	/**
	 * Execute Non-query
	 *
	 * @return boolean 
	 */
	public function executeNonQuery($query) {
		$result = mysql_query($query, $this->con);
		return $result;
	}
	
	/**
	 * Execute Scalar
	 *
	 * @return single row or null
	 */
	public function executeScalar($query) {
		$result = null;
		$query = preg_replace('/ LIMIT.*$/', '', $query);
		$query .= " LIMIT 0, 1";

		$lst = mysql_query($query, $this->con);
		if ($lst) $result = mysql_fetch_assoc($lst);
		return $result;
	}
	
	/**
	 * Get Last Inserted Row ID
	 *
	 * @return int
	 */
	public function getInsertID() {
		return mysql_insert_id();
	}

	/**
	 * Get Sql Escape String
	 *
	 * @return string
	 */
	public function escapeSql($str) {
		return mysql_real_escape_string($str);
	}
}

class QueryIterator {
	
	private $_resource = null;
	
	public function __construct($resource) {
		$this->_resource = $resource;
	}
	
	/**
	 * Get row
	 *
	 * @return associate array
	 */
	public function getRow() {
		return mysql_fetch_assoc($this->_resource);
	}
}